<?php

namespace app\modules\backend\controllers;

use app\filters\auth\HttpBearerAuth;
use app\models\Base;
use app\models\User;
use app\models\Admin;
use app\models\ActionRecord;
use app\models\BrandStatistics;
use app\models\LiveLb;
use app\tools\Re;
use app\tools\Rongyun;
use app\tools\Tool;
use yii\helpers\Inflector;
use Yii;
use yii\web\Response;
use yii\rest\Controller;
use yii\web\UnauthorizedHttpException;
use app\models\Identity;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;
date_default_timezone_set('PRC');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers:*');

/**
 * Default controller for the `admin` module
 */
class BaseController extends Controller
{

    public function behaviors(){
        $behaviors = parent::behaviors();
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            $behaviors['authenticator'] = [
                'class' => HttpBearerAuth::class
            ];
        }
        return $behaviors;
    }

    /**
     * @param $action
     * @return bool
     * @throws UnauthorizedHttpException
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
      parent::beforeAction($action);
      Yii::$app->response->format = Response::FORMAT_JSON;
      if ($action->id != 'login' && !empty(Yii::$app->user->id)) {
        $post = Yii::$app->request->post();
        $action_record = new ActionRecord();
        $action_record->admin_id = (string)Yii::$app->user->id;
        $action_record->ip = Yii::$app->request->userIP;
        $action_record->controller_id = $action->controller->id;
        $action_record->action_id = $action->id;
        $action_record->post_data = json_encode($post);
        $action_record->created_at = time();
        $action_record->save();
      }
      /*$authorization = Yii::$app->request->post('authorization', 0);
      if ($action->controller->id == 'permission') {
        return true;
      }
      $ip = $_SERVER["REMOTE_ADDR"];
      $redis_key = 'intercept_pc::' . $action->controller->id .'::' . $action->id . '::' . $ip . '::' . $authorization;
      $redis_value = Yii::$app->redis->get($redis_key);
      if ($redis_value) {
        Yii::$app->response->data = array(
          'code' => 403,
          'text' => '操作频繁，请稍后再试'
        );
        return false;
      }
      Yii::$app->redis->psetex($redis_key, 500, 1);*/
      //Yii::$app->redis->expire($redis_key, 1);
      return true;
    }

    /**
     * @param Base|string $model_name
     * @param int $id
     * @param array $data
     * @return mixed
     */
    public function edit($model_name, $id = 0, $data = []){
        if($id){
            $model = $model_name::findOne($id);
            if(!$model){
                return Re::data(null, '您修改的数据不存在', Re::ERROR);
            }
        }else{
            $model = new $model_name();
        }

        $model->load($data, '');

        if($model->save()){
            $re_data = [];
            foreach ($data as $k=>$v) {
                $method_name = 'show'.Inflector::camelize($k);
                if(method_exists($model, $method_name)){
                    $re_data[$k] = $model->$method_name();
                }elseif(array_key_exists($k, $model->attributes)){
                    $re_data[$k] = $model->$k;
                }else{
                    $re_data[$k] = $v;
                }
            }
            $re_data['id'] = $model->id;
            return Re::data(['data'=>$re_data]);
        }else{
            return Re::data(null, $model->showErrors(), Re::ERROR);
        }
    }
}
